package com.whiteape.book.ui.adapter;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.Headers;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.github.chrisbanes.photoview.OnPhotoTapListener;
import com.github.chrisbanes.photoview.OnScaleChangedListener;
import com.github.chrisbanes.photoview.PhotoView;
import com.whiteape.book.R;
import com.whiteape.book.model.bo.ChapterContentBo;
import com.whiteape.book.utils.DisplayUtil;
import com.whiteape.book.utils.LogUtils;
import com.whiteape.book.utils.StringUtils;
import com.whiteape.book.widget.ComicLoadingDrawable;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ComicReadAdapter extends BaseQuickAdapter<ChapterContentBo, BaseViewHolder> {

    //    View.OnTouchListener listener;
    OnPhotoTapListener listener;
    OnLazyLoadListener lazyLoadListener;
    String userAgent;
    boolean loadSuccess = true;

    View.OnTouchListener touchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()){
                case MotionEvent.ACTION_DOWN:
                    view.setScaleX(0.95f);
                    view.setScaleY(0.95f);
                    break;
                case MotionEvent.ACTION_UP:
                    view.setScaleX(1f);
                    view.setScaleY(1f);
                    break;
            }
            return false;
        }
    };

    public ComicReadAdapter(int layoutResId, @Nullable List<ChapterContentBo> data) {
        super(layoutResId, data);
    }

    public void setUserAgent(String userAgent){
        this.userAgent = userAgent;
    }

    public void setTapListener(OnPhotoTapListener listener) {
        this.listener = listener;
    }

    public void setLazyLoadListener(OnLazyLoadListener listener) {
        this.lazyLoadListener = listener;
    }

    @Override
    protected void convert(BaseViewHolder helper, ChapterContentBo item) {
        ImageView imageView = helper.getView(R.id.pv_comic);
        TextView mask = helper.getView(R.id.tv_mask);
//        helper.setText(R.id.tv_num, "" + (item.getCurPartNum() + 1));
        helper.addOnClickListener(R.id.pv_comic);
        helper.addOnClickListener(R.id.tv_mask);
//        PhotoView imageView= helper.getView(R.id.pv_comic);
//        imageView.setOnScaleChangeListener(new OnScaleChangedListener() {
//            @Override
//            public void onScaleChange(float scaleFactor, float focusX, float focusY) {
//
//            }
//        });
        final int position = getData().indexOf(item);

        mask.setOnTouchListener(touchListener);
        mask.setOnClickListener(view -> {
            if (!loadSuccess) {
                loadImg(position, item, imageView, mask);
                return;
            }
            view.setVisibility(View.GONE);
        });
        imageView.setOnClickListener(v -> {
            listener.onPhotoTap(imageView, 0,0);
        });
//        ((PhotoView) helper.getView(R.id.pv_comic)).setOnPhotoTapListener((view, x, y) -> {
//            if (!loadSuccess) {
//                loadImg(item, imageView);
//                return;
//            }
//            listener.onPhotoTap(view, x, y);
//        });
        Boolean lazyLoading = item.getLazyLoading();
        if (lazyLoading != null && lazyLoading) {
            imageView.setImageResource(R.mipmap.pic_default_vertical);
            if (lazyLoadListener != null) {
                lazyLoadListener.lazyLoad(item);
            } else {
                LogUtils.d("No lazy load listener");
            }

            return;
        }

        loadImg(position, item, imageView, mask);

//        ((PhotoView) helper.getView(R.id.pv_comic)).setOnTouchListener(listener);
    }

    private void loadImg(int position, ChapterContentBo item, ImageView imageView, TextView mask) {

        if(StringUtils.isEmpty(item.getContent())){
            return;
        }
        GlideUrl url = new GlideUrl(item.getContent(), () -> {
            Map<String, String> headers = new HashMap<String, String>();

            headers.put("User-Agent",userAgent);
            if (item.getHeaders() != null) {
                headers.putAll(item.getHeaders());
            }
//            headers.put("Referer", item.getCurrentChapterLink());
            return headers;
        }
        );
        int screenHeight = DisplayUtil.getScreenHeight(mContext);
        int screenWidth = DisplayUtil.getScreenWidth(mContext);

        Glide.with(mContext)
                .load(item.getContent().startsWith("http") ? url : item.getContent())
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .transition(DrawableTransitionOptions.withCrossFade(300))
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        loadSuccess = false;
                        imageView.setTag(R.id.iv_tag, false);
//                        mask.setVisibility(View.VISIBLE);

//                        ViewGroup.LayoutParams params = imageView.getLayoutParams();
//                        params.height = DisplayUtil.getScreenHeight(mContext);
//                        params.width = DisplayUtil.getScreenWidth(mContext);
//                        imageView.setLayoutParams(params);
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        loadSuccess = true;
                        mask.setVisibility(View.GONE);
                        if (imageView == null) {
                            return false;
                        }
                        imageView.setTag(R.id.iv_tag, true);
                        if (imageView.getScaleType() != ImageView.ScaleType.FIT_XY) {
                            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        }
                        ViewGroup.LayoutParams params = imageView.getLayoutParams();
                        int vw = imageView.getWidth() - imageView.getPaddingLeft() - imageView.getPaddingRight();
                        float scale = (float) vw / (float) resource.getIntrinsicWidth();
                        int vh = Math.round(resource.getIntrinsicHeight() * scale);
                        params.height = vh + imageView.getPaddingTop() + imageView.getPaddingBottom();
                        imageView.setLayoutParams(params);


                        return false;
                    }
                })
//                .error(R.drawable.retry)
                .error(R.mipmap.pic_failed_vertical)
                .placeholder(R.mipmap.pic_default_vertical)
//                .placeholder(new ComicLoadingDrawable(screenWidth,screenHeight, Color.parseColor("#000000"),position) )
                .override(Target.SIZE_ORIGINAL,Target.SIZE_ORIGINAL)
                .into(imageView)
        ;
    }

    public void lazyLoadSuccess(ChapterContentBo bo) {
        int size = mData.size();

        //TODO 优化搜索，用map chapterId + partNum作为key
        for (int i = 0; i < size; i++) {
            ChapterContentBo chapterContentBo = mData.get(i);
            if (bo.getChapterId().equals(chapterContentBo.getChapterId()) &&
            bo.getCurPartNum().equals(chapterContentBo.getCurPartNum())) {
                chapterContentBo.setContent(bo.getContent());
                chapterContentBo.setLazyLoading(false);
//                notifyDataSetChanged();
                notifyItemChanged(i);
                return;
            }
        }

    }

    public interface OnLazyLoadListener {
        void lazyLoad(ChapterContentBo chapterContentBo);
    }
}
